#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
WHITE='\033[1;37m'
NC='\033[0m' # No Color

# 彩色输出函数
info() { echo -e "${GREEN}[信息]${NC} $1"; }
warn() { echo -e "${YELLOW}[警告]${NC} $1"; }
error() { echo -e "${RED}[错误]${NC} $1"; exit 1; }
title() { echo -e "${BLUE}$1${NC}"; }

# 检查root权限
[ "$(id -u)" != "0" ] && error "此脚本需要root权限执行!"

# 系统版本检查
if ! grep -q "CentOS Linux release 7" /etc/centos-release 2>/dev/null; then
    error "此脚本仅适用于CentOS 7系统!"
fi

# 欢迎信息
title "================================================"
title "          Syncthing 自动安装脚本 (CentOS 7专用)"
title "================================================"
info " 功能说明:"
info " 1. 安装必要依赖 (wget/tar/git)"
info " 2. 从Gitee仓库下载Syncthing v1.29.5"
info " 3. 解压并安装到/opt/syncthing"
info " 4. 创建systemd服务并启动"
info " 5. 设置开机自启"
info " 6. 配置防火墙规则 (可选)"
info ""
info " 项目仓库地址: https://gitee.com/cncsrf/install_syncthing"
warn ""
warn " 注意: 安装前请确保:"
warn " 1. 您有root权限"
warn " 2. 服务器能正常访问Gitee"
warn " 3. 8384, 22000等端口未被占用"
title "================================================"

# 确认安装
read -p "是否继续安装? [Y/n] " confirm
if [[ $confirm =~ ^[Nn]$ ]]; then
    info "已取消安装"
    exit 0
fi

# 安装依赖
info "正在安装依赖..."
sudo yum install -y wget tar git || error "依赖安装失败!"

# 克隆仓库或下载安装包
info "正在获取Syncthing安装包..."
if command -v git &> /dev/null; then
    git clone https://gitee.com/cncsrf/install_syncthing.git || error "克隆仓库失败!"
    cd install_syncthing
else
    wget https://gitee.com/cncsrf/install_syncthing/repository/archive/master.zip || error "下载安装包失败!"
    unzip master.zip || error "解压安装包失败!"
    mv install_syncthing-master install_syncthing
    cd install_syncthing
fi

# 检查安装包是否存在
[ ! -f "syncthing-linux-amd64-v1.29.5.tar.gz" ] && error "未找到 syncthing-linux-amd64-v1.29.5.tar.gz 文件"

# 解压文件
info "正在解压安装包..."
tar -zxvf syncthing-linux-amd64-v1.29.5.tar.gz || error "解压失败!"

# 移动到 /opt/syncthing
info "正在安装到/opt/syncthing..."
sudo mv syncthing-linux-amd64-v1.29.5 /opt/syncthing || error "移动文件失败!"

# 创建 systemd 服务文件
info "正在配置系统服务..."
sudo bash -c "cat > /etc/systemd/system/syncthing.service <<EOL
[Unit]
Description=Syncthing - Open Source Continuous File Synchronization
Documentation=man:syncthing(1)
After=network.target

[Service]
User=root
ExecStart=/opt/syncthing/syncthing -no-browser -gui-address=0.0.0.0:8384 --logflags=0
Restart=on-failure
RestartSec=1
KillMode=process
SuccessExitStatus=3 4
RestartForceExitStatus=3 4

# Hardening (可选)
ProtectSystem=full
PrivateTmp=true
SystemCallArchitectures=native
MemoryDenyWriteExecute=true
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
EOL" || error "创建服务文件失败!"

# 重新加载 systemd 配置
sudo systemctl daemon-reload || warn "systemd配置重载失败!"

# 启动 Syncthing 服务
info "正在启动服务..."
sudo systemctl start syncthing || error "服务启动失败!"

# 设置开机自启
sudo systemctl enable syncthing || warn "设置开机自启失败!"

# 检查服务状态
info "服务状态检查..."
sleep 3
systemctl status syncthing --no-pager -l || warn "服务状态检查失败!"

# 解决IPv6监听问题 - 强制监听所有IP
info "配置网络监听..."
[ -f "/root/.config/syncthing/config.xml" ] && sudo sed -i 's/<address>127.0.0.1:8384<\/address>/<address>0.0.0.0:8384<\/address>/g' /root/.config/syncthing/config.xml
sudo systemctl restart syncthing || warn "服务重启失败!"

# 防火墙配置
title "================================================"
info "           防火墙配置"
info "Syncthing需要以下端口："
info "TCP: 8384 (Web界面), 22000 (同步)"
info "UDP: 21027 (发现)"
warn "注意: 错误的防火墙配置可能导致服务不可用!"
title "================================================"

read -p "是否自动配置防火墙规则? [Y/n] " firewall_confirm

if [[ ! $firewall_confirm =~ ^[Nn]$ ]]; then
    info "正在配置防火墙..."
    
    # 备份防火墙规则
    backup_time=$(date +%Y%m%d%H%M%S)
    if systemctl is-active --quiet firewalld; then
        info "正在备份firewalld规则到 /etc/firewalld/firewalld_backup_${backup_time}.xml"
        sudo firewall-cmd --list-all > "/etc/firewalld/firewalld_backup_${backup_time}.xml" || warn "firewalld规则备份失败!"
        info "如需恢复备份，请执行: sudo firewall-cmd --restore=/etc/firewalld/firewalld_backup_${backup_time}.xml"
    elif command -v iptables &> /dev/null; then
        info "正在备份iptables规则到 /etc/sysconfig/iptables_backup_${backup_time}"
        sudo cp /etc/sysconfig/iptables "/etc/sysconfig/iptables_backup_${backup_time}" || warn "iptables规则备份失败!"
        info "如需恢复备份，请执行: sudo cp /etc/sysconfig/iptables_backup_${backup_time} /etc/sysconfig/iptables && sudo service iptables restart"
    fi
    
    # 配置防火墙规则
    if systemctl is-active --quiet firewalld; then
        sudo firewall-cmd --permanent --add-port=8384/tcp || warn "添加8384端口失败!"
        sudo firewall-cmd --permanent --add-port=22000/tcp || warn "添加22000端口失败!"
        sudo firewall-cmd --permanent --add-port=21027/udp || warn "添加21027端口失败!"
        sudo firewall-cmd --reload || warn "防火墙重载失败!"
        info "Firewalld规则已添加"
    elif command -v iptables &> /dev/null; then
        sudo iptables -I INPUT -p tcp --dport 8384 -j ACCEPT || warn "添加8384规则失败!"
        sudo iptables -I INPUT -p tcp --dport 22000 -j ACCEPT || warn "添加22000规则失败!"
        sudo iptables -I INPUT -p udp --dport 21027 -j ACCEPT || warn "添加21027规则失败!"
        sudo service iptables save || warn "规则保存失败!"
        info "iptables规则已添加"
    else
        warn "未检测到防火墙服务，请手动配置"
    fi
else
    warn "请手动确保以下端口已开放："
    warn "TCP: 8384, 22000"
    warn "UDP: 21027"
fi

# 显示安装完成信息
title "================================================"
info "          安装完成"
info "Syncthing 已成功安装并启动！"
info "Web界面: http://<服务器IP>:8384"
info ""
info "后续操作建议："
info "1. 首次访问Web界面设置管理员密码"
info "2. 配置设备ID和同步文件夹"
info "3. 添加远程设备"
info ""
info "项目仓库地址: https://gitee.com/cncsrf/install_syncthing"
title "================================================"

# 清理临时文件
cd ..
rm -rf install_syncthing